import React, { useState, useRef } from 'react';
import { Row, Col, DatePicker, Divider, Button, Switch, Tooltip, message } from 'antd';
import AutoTable from '@/components/AutoTable';
import IconFont from '@/components/IconFont';
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts';
import { Map, Marker } from 'react-amap';
import { RollbackOutlined } from '@ant-design/icons';
import { device_count, history_record } from '@/services/api';
import moment from 'moment';
import { useRequest } from 'ahooks';
import { doFetch } from '@/utils/doFetch';

let col = { xs: 24, sm: 24, md: 12, lg: 6, xl: 6, xxl: 6 },
  cols = { xs: 24, sm: 24, md: 12, lg: 12, xl: 12, xxl: 12 },
  colc = { xs: 24, sm: 24, md: 12, lg: 18, xl: 18, xxl: 18 },
  cold = { xs: 24, sm: 24, md: 24, lg: 12, xl: 12, xxl: 12 },
  { RangePicker } = DatePicker;

let format = 'YYYY-MM-DD';

export default () => {
  let [center, setcenter] = useState({ longitude: 114.053622, latitude: 22.560047 }),
    actionRef = useRef(),
    [cur, setcur] = useState(''),
    [params, setparams] = useState({
      start_time: moment().add('day', -7).format(format),
      end_time: moment().format(format),
    });

  const { data } = useRequest(() => device_count(params), {
    refreshDeps: [params],
  }),
    res = useRequest(
      () => history_record({ start_date: params.start_time, end_date: params.end_time }),
      {},
    );


  let columns = [
    // {
    //   title: '设备名',
    //   dataIndex: 'name',
    //   key: 'name',
    //   render: (dom, row) => {
    //     return (
    //       <a className={cur.id == row.id ? 'cur' : ''}>
    //         {row.name}
    //         &nbsp;
    //       </a>
    //     );
    //   },
    // }, 
    {
      title: '设备状态',
      dataIndex: 'is_online',
      key: 'is_online',
      render: (dom, row) => {
        return (
          <a>
            {row.is_online ? (
              <Tooltip title="在线">
                <span>
                  在线
                </span>
                <IconFont type="icon-online" className="green"></IconFont>
              </Tooltip>
            ) : (
              <Tooltip title="离线">
                <span>
                  离线
                </span>
                <IconFont type="icon-offline" className="grey"></IconFont>
              </Tooltip>
            )}
          </a>
        );
      },
    },

    {
      title: '具体地址',
      dataIndex: 'address',
      key: 'address',
      search: false,
    },
    {
      title: '火焰报警',
      dataIndex: 'flame_value',
      key: 'flame_value',
      search: false,
      render: (_, row) => {
        if (row.flame_value) {
          return (
            <div className="animateopacty startcenter">
              <span className="red">有</span>&nbsp;
              <IconFont type="icon-fire" style={{ fontSize: 20 }}></IconFont>
            </div>
          );
        } else {
          return (
            <div className="startcenter">
              <span>无</span>&nbsp;
              <IconFont type="icon-fire1" style={{ fontSize: 20 }}></IconFont>
            </div>
          );
        }
      },
    },
    {
      title: '烟雾报警',
      dataIndex: 'smoke_value',
      key: 'smoke_value',
      search: false,
      render: (_, row) => {
        if (row.smoke_value) {
          return (
            <div className="animateopacty startcenter">
              <span className="red">有</span>&nbsp;
              <IconFont type="icon-smoke" className="red" style={{ fontSize: 20 }}></IconFont>
            </div>
          );
        } else {
          return (
            <div className="startcenter">
              <span>无</span>&nbsp;
              <IconFont type="icon-smoke" style={{ fontSize: 20 }}></IconFont>
            </div>
          );
        }
      },
    },
    {
      title: '主管道水压',
      dataIndex: 'water_pressure_value',
      key: 'water_pressure_value',
      search: false,
      render: (_, row) => {
        if (row.water_pressure_value) {
          return (
            <div className="animateopacty startcenter">
              <span className="red">有</span>&nbsp;
              <IconFont type="icon-shuiya" className="red" style={{ fontSize: 24 }}></IconFont>
            </div>
          );
        } else {
          return (
            <div className="startcenter">
              <span>无</span>&nbsp;
              <IconFont type="icon-shuiya" style={{ fontSize: 24 }}></IconFont>
            </div>
          );
        }
      },
    },
    {
      title: '喷洒指示',
      dataIndex: 'spray_value',
      key: 'spray_value',
      search: false,
      render: (_, row) => {
        if (row.spray_value) {
          return (
            <div className="animateopacty startcenter">
              <span className="red">有</span>&nbsp;
              <IconFont type="icon-pensa" style={{ fontSize: 26 }} className="red"></IconFont>
            </div>
          );
        } else {
          return (
            <div className="startcenter">
              <span>无</span>&nbsp;
              <IconFont type="icon-pensa" style={{ fontSize: 26 }}></IconFont>
            </div>
          );
        }
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 80,
      render: (text, record, _, action) => [
        // eslint-disable-next-line react/jsx-key
        <Switch checked={!record.spray_value} checkedChildren="开启" unCheckedChildren="关闭" onClick={() => {
          doFetch({ url: "/vehicle-api/device/output_water_pressure", params: { id: record.id, is_open: !record.spray_value }, type: "PUT" }).then(res => {
            if (res.code == 0) {
              message.success("操作成功");
              actionRef?.current?.reload()
            }
          })
        }} />,
      ],
    },
  ],
    columnes = [
      {
        title: '报警位置',
        dataIndex: 'alarm_address',
        key: 'alarm_address',
        render: (dom, row) => {
          return (
            <a
              onClick={() => {
                setcenter({
                  longitude: row?.lng,
                  latitude: row?.lat,
                });
              }}
            >
              {dom}
            </a>
          );
        },
      },
      {
        title: '报警时间',
        dataIndex: 'alarm_time',
        key: 'alarm_time',
        search: false,
        render: (_, row) => {
          return <span className="oneline">{moment(row.alarm_time).format('YYYY-MM-DD HH:mm')}</span>;
        },
      },
      {
        title: '查看监控',
        dataIndex: 'alarm_type',
        key: 'alarm_type',
        search: false,
        render: (dom, row) => {
          return (
            <a className='rows' style={{ display: "flex", alignItems: "center" }}>
              <IconFont
                style={{ fontSize: 12, paddingRight: 12 }}
                type="icon-jiankong"
                onClick={() => {
                  window.open(
                    'https://open.ys7.com/ezopen/h5/iframe?url=ezopen://open.ys7.com/G63780146/1.hd.live&autoplay=1&accessToken=at.085h4vfk422g84j28wmorzb72ews2ijp-6ij50esum2-11gohbs-sjpldjnyt',
                  );
                }}
              />
              查看监控
            </a>
          );
        },
      },
    ];

  let disabledStartDate = (start_time) => {
    const { end_time } = params;
    if (!start_time || !end_time) {
      return false;
    }
    return moment(start_time).valueOf() > moment(end_time).valueOf();
  },
    disabledEndDate = (end_time) => {
      const { start_time } = params;
      if (!end_time || !start_time) {
        return false;
      }
      return moment(end_time).valueOf() <= moment(start_time).valueOf();
    },
    onChange = (field, value) => {
      setparams((params) => {
        return {
          ...params,
          [field]: value,
        };
      });
    };

  return (
    <div style={{ width: '100%', height: '100%', padding: 12 }}>
      <div
        className="blur"
        style={{
          display: 'flex',
          flexDirection: 'column',
          width: '100%',
          minHeight: '100%',
          padding: 12,
        }}
      >
        <Row style={{ marginBottom: 12, overflow: 'hidden' }}>
          <Col
            {...col}
            style={{
              display: 'flex',
              flexDirection: 'column',
              overflow: 'hidden',
              padding: 12,
            }}
            className="columns"
          >
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                width: '100%',
              }}
            >
              <DatePicker
                picker="month"
                style={{ flex: 1 }}
                disabledDate={disabledStartDate}
                value={moment(params.start_time)}
                onChange={(val) => {
                  onChange(
                    'start_time',
                    val ? moment(val).format(format) : moment().format(format),
                  );
                }}
              />
              <div style={{ color: '#fff', padding: '0 12px' }}>-</div>
              <DatePicker
                picker="month"
                style={{ flex: 1 }}
                disabledDate={disabledEndDate}
                value={moment(params.end_time)}
                onChange={(val) => {
                  onChange('end_time', val ? moment(val).format(format) : moment().format(format));
                }}
              />
            </div>
            <div
              style={{
                display: 'flex',
                width: '100%',
                justifyContent: 'center',
                alignItems: 'center',
                margin: '36px 0 0 0 ',
                flex: 1,
              }}
              gutter={24}
            >
              <div className="ng">
                <span>
                  <b>{data?.data?.online ?? 4}</b>台
                </span>
                <span>设备在线数量</span>
              </div>
              <div style={{ color: '#fff', padding: '0 14px' }} />
              <div className="ng" style={{ backgroundColor: '#ff8434' }}>
                <span>
                  <b>{data?.data?.alarm ?? 2}</b>台
                </span>
                <span>设备报警数量</span>
              </div>
            </div>
          </Col>
          <Col
            {...cols}
            style={{
              display: 'flex',
              flexDirection: 'column',
              overflow: 'hidden',
              padding: 12,
            }}
          >
            <p
              style={{
                color: '#fff',
                display: 'inline-block',
                fontSize: 16,
                marginBottom: 12,
              }}
            >
              历史报警统计图
            </p>
            <div style={{ flex: 1, overflow: 'hidden' }}>
              <ReactECharts
                style={{ height: '30vh', width: '100%' }}
                option={{
                  tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                      type: 'cross',
                      label: {
                        backgroundColor: '#6a7985',
                      },
                    },
                  },
                  grid: {
                    left: '0px',
                    right: '12px',
                    bottom: '0px',
                    top: '12px',
                    containLabel: true,
                  },
                  xAxis: {
                    type: 'category',
                    data: res?.data && res?.data?.data.map((it) => it.date),
                    axisLine: {
                      lineStyle: {
                        color: '#089eb2',
                        width: 1,
                      }
                    }
                  },
                  yAxis: {
                    type: 'value',
                    axisLine: {
                      show: true,
                      lineStyle: {
                        color: 'rgb(8, 158, 175,0.8)',
                        width: 1,
                      }
                    },
                    splitLine: {
                      lineStyle: {
                        type: "dashed",
                        color: 'rgb(253, 236, 75,0.2)',
                        width: 1,
                      }
                    }
                  },
                  series: [
                    {
                      data: res?.data && res?.data?.data.map((it) => it.count),
                      type: 'line',
                      label: {
                        show: true,
                        position: 'bottom',
                        color: '#fff',
                      },
                      lineStyle: {
                        color: '#fdec4b',
                        width: 1
                      },
                      itemStyle: {
                        normal: {
                          width: 1,
                          height: 1,
                          color: '#fdec4b',
                          borderColor: "#fdec4b"
                        }
                      },
                      areaStyle: {
                        color: echarts.graphic.LinearGradient(0, 0, 0, 1, [
                          {
                            offset: 0,
                            color: 'rgb(253, 236, 75,0.5)',
                          },
                          {
                            offset: 1,
                            color: 'rgb(253, 236, 75,0)',
                          },
                        ]),
                      },
                    },
                  ],
                }}
              />
            </div>
          </Col>
          <Col
            {...col}
            style={{
              display: 'flex',
              flexDirection: 'column',
              overflow: 'hidden',
              padding: 12,
            }}
          >
            <p
              style={{
                color: '#fff',
                display: 'block',
                marginBottom: -12,
                fontSize: 16,
              }}
            >
              实时报警信息
            </p>
            <AutoTable
              path="/vehicle-api/monitor/fire_control_list"
              rowClassName={(record, index) => {
                let className = index % 2 ? 'shallow_gray' : 'deep_gray';
                return className;
              }}
              columns={columnes}
              bordered={false}
              withCard={false}
              style={{ height: 'auto', marginTop: 20 }}
              onlyTable={true}
            />
          </Col>
        </Row>
        <Row style={{ flex: 3, overflow: 'hidden' }}>
          <Col
            {...colc}
            style={{
              display: 'flex',
              flexDirection: 'column',
              overflow: 'hidden',
              padding: 12,
            }}
          >
            <AutoTable
              path="/vehicle-api/device"
              actionRef={actionRef}
              rowClassName={(record, index) => {
                let className = index % 2 ? 'shallow_gray' : 'deep_gray';
                return className;
              }}
              columns={columns}
              withCard={false}
              bordered={false}
              style={{ height: 'auto', marginTop: -20 }}
              onlyTable={true}
              onRow={(record) => {
                setcur(record);
                setcenter({
                  longitude: record.lng,
                  latitude: record.lat,
                });
              }}
            />
          </Col>
          <Col {...col} style={{ display: 'flex', overflow: 'hidden', padding: 12, flexDirection: "column" }}>
            <div style={{ width: '100%', flex: 1, minHeight: '30vh' }}>
              <Map
                center={center}
                pitch={60}
                viewMode="3D"
                mapStyle="amap://styles/light"
                zoom={18}
                style={{ position: 'relative' }}
                rotation={15}
              >
                <Marker
                  position={center}
                />

                <Button
                  style={{ cursor: 'pointer' }}
                  type="primary"
                  onClick={() => {
                    setcenter({ ...center });
                  }}
                  icon={<RollbackOutlined />}
                  // eslint-disable-next-line react/jsx-no-duplicate-props
                  style={{ position: 'absolute', right: 12, top: 12 }}
                />
              </Map>
            </div>
            <div className='center' style={{ color: "#fff", height: 56, fontSize: 16, fontWeight: "bolder" }}>
              {cur?.address ?? "-"}
            </div>
          </Col>
        </Row>
      </div>
    </div>
  );
};
